package com.comet.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 限流、熔断返回信息
 */
@Component
public class SentinelBlockException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (e instanceof FlowException) {
            map.put("code",-100);
            map.put("msg","限流异常");
        }else if (e instanceof DegradeException) {
            map.put("code",-101);
            map.put("msg","降级异常");
        }else if (e instanceof ParamFlowException) {
            map.put("code",-102);
            map.put("msg","参数限流异常");
        }else if (e instanceof SystemBlockException) {
            map.put("code",-103);
            map.put("msg","系统异常");
        }else if (e instanceof AuthorityException) {
            map.put("code",-104);
            map.put("msg","授权异常");
        }

        httpServletResponse.setStatus(200);
        httpServletResponse.setHeader("content-type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(map));

    }
}
